class Solution {
public:
    int deleteAndEarn(vector<int>& nums)
    {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        vector<int> dp(nums[n - 1] + 1);
        for (auto x : nums)dp[x] += x;
        int n2 = dp.size();
        vector<int> f(n2), g(n2);

        for (int i = 1; i < n2; i++)
        {
            f[i] = g[i - 1] + dp[i];
            g[i] = max(f[i - 1], g[i - 1]);
        }
        return max(f[n2 - 1], g[n2 - 1]);

    }
};